package com.tj.collection.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.tj.collection.bean.SystemConstants;
import com.tj.collection.db.enums.RoleKeyEnum;
import com.tj.collection.db.service.AdminRoleService;
import com.tj.collection.integration.ProductIntegrationService;
import com.tj.collection.utils.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户角色菜单权限同步
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/10/10
 * Time: 上午10:13
 */
@Component
public class MerchantMenuSyncTask implements SimpleJob {

    public static final Log LOGGER = LogFactory.getLog(MerchantMenuSyncTask.class);

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private ProductIntegrationService productIntegrationService;

    @Override
    public void execute(ShardingContext shardingContext) {
        LOGGER.info("商户角色菜单权限同步任务开始");
        try {
            if (!configUtil.getMerchantMenuSyncSwitch()) {
                LOGGER.info("商户角色菜单权限同步任务未开启");
                return;
            }
            List<RoleKeyEnum> roleKeyEnumList = Lists.newArrayList(
                    RoleKeyEnum.SUPERADMIN,
                    RoleKeyEnum.COLLECT_LEADER,
                    RoleKeyEnum.THIRD_COLLECT_LEADER,
                    RoleKeyEnum.COLLECT_STAFF
            );

            List<ProductCategory> productCategoryList = productIntegrationService.getAllActiveProductCategory().getData();
            List<String> merchantCodeList = productCategoryList.stream().map(productCategory -> productCategory.getMerchantCode()).collect(Collectors.toList());
            merchantCodeList = merchantCodeList.stream().distinct().collect(Collectors.toList());
            for (String merchantCode : merchantCodeList) {
                if (SystemConstants.CASHMAMA.equals(merchantCode)) {
                    continue;
                }
                for (RoleKeyEnum roleKeyEnum : roleKeyEnumList) {
                    adminRoleService.syncRoleAndMenu(roleKeyEnum.getType(), SystemConstants.CASHMAMA, merchantCode);
                    LOGGER.info("商户角色菜单权限同步成功,roleKey:{},merchantCode:{}", roleKeyEnum.getType(), merchantCode);
                }
            }
            LOGGER.info("商户角色菜单权限同步任务结束");
        } catch (Exception e) {
            LOGGER.error("商户角色菜单权限同步任务异常", e);
        }
    }


}
